/**
 * Copyright (C) 2012 The SkyTvOS Project
 * <p/>
 * Version     Date           Author
 * ─────────────────────────────────────
 * 2013-9-3         Rico
 */

package com.tianci.appstore.utils;

import java.util.LinkedList;

public class SkyTaskRunnablePool {
    private LinkedList<SkyRunnable> tasks;
    private boolean limitTask = false;

    public SkyTaskRunnablePool(boolean limitTask) {
        tasks = new LinkedList<SkyRunnable>();
        this.limitTask = limitTask;
    }

    public synchronized void putTask(SkyRunnable task) {
        if (tasks.size() == 0) {
            tasks.add(task);
        } else {
            if (task.getRunnableId() == null) {
                System.out.println(getClass().getName() + ": callback id  == null");
                return;
            }
            if (task.getRunnableId().equals("")) {

                System.out.println(getClass().getName() + ": callback id  == \"\"");
                return;
            }

            if (limitTask && tasks.size() > 24) {
//            	LogUtils.d("thread","task size  reach:"+tasks.size());
                tasks.remove(0);
            }

            boolean added = false;
//            for (int i = 0; i < tasks.size(); i++)
//            {
//                
//                if (task.getRunnableId().equals(tasks.get(i).getRunnableId()))
//                {
//                    tasks.remove(i);
//                    tasks.add(i, task);
//                    added = true;
//                    break;
//                }
//            }
            if (!added) {
                tasks.addLast(task);
            }
        }
    }

    public synchronized void cleanup() {
        tasks.clear();
    }

    public synchronized SkyRunnable getTask() {
        if (tasks.size() > 0) {
            return tasks.poll();
        }
        return null;
    }

    public int getSize() {
        return tasks.size();
    }
}
